package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
/**
 * @WebFilter注解：
 */
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    /**
     * 初始化
     *
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       log.debug("过滤器初始化...");
    }
    /**
     * 核心过滤方法:用户登录校验 网站限流 日志记录 性能监控
     *
     */

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("开始进行用户登录校验的过滤器...");
        //1.类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2获取会话HttpSession
        HttpSession session = request.getSession();
        //获取用户标识
        UserVO userVO = (UserVO) session.getAttribute("user");
        //4判断
        if (userVO != null){//登陆状态没问题
            filterChain.doFilter(request,response);//有这行代表放行
        }
        else {
            response.sendRedirect("/login.html");
        }

    }
    /**
     * 过滤器销毁
     *
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
